package com.dtguai.admin.util.redis;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author guoLiang
 * @date 2018-09-29 03:46:03
 */
@Component
public class RedisUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;


    public static final int TIME_OUT_DEF = 60 * 60 * 2;

    public static final int TIME_OUT_DAY = 60 * 60 * 24;


    public <T> T getModel(String key, Class<T> clazz) {
        String json = redisTemplate.opsForValue().get(key);
        return JSON.parseObject(json, clazz);
    }

    public String getString(String key) {
        return redisTemplate.opsForValue().get(key);
    }


    public void delete(String key) {
        redisTemplate.delete(key);
    }


    /**
     * String set 系列
     */
    public void setString(String key, String value) {
        setString(key, value, TIME_OUT_DEF);
    }

    /**
     * 插入缓存
     *
     * @param key   key
     * @param value 字符串内容
     * @param time  时间单位:秒
     */
    public void setString(String key, String value, Integer time) {
        setString(key, value, time, TimeUnit.SECONDS);
    }

    public void setString(String key, String value, Integer time, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, time, timeUnit);
    }

    /**
     * hash get 系列
     */
    public Object getHash(String hashKey, String key) {
        return redisTemplate.opsForHash().get(hashKey, key);
    }

    /**
     * hash set 系列
     */
    public void setHash(String collectionKey, Object key, Object value, Integer time) {
        redisTemplate.opsForHash().put(collectionKey, key.toString(), JSON.toJSONString(value));
        redisTemplate.expire(collectionKey, TIME_OUT_DEF, TimeUnit.SECONDS);
    }


}